#!/usr/bin/env bash


function yesno()
{
    local answer
    while [[ "$answer" != "y" && "$answer" != "n" ]]; do
        read -p "$1" answer
        case "$answer" in
        y|Y)
            answer="y"
            ;;
        n|N)
            answer="n"
            ;;
        *)
            answer=""
            ;;
        esac
    done
    [[ "$answer" = "y" || "$answer" == "yes" ]]
}

while [[ -z "$role" ]]; do
    read -p "controller or worker?" role
done
while [[ -z "$cip" ]]; do
    read -p "controller nfs ip?" cip
done
while [[ -z "$chome" ]]; do
    read -p "controller home?" chome
done
while [[ -z "$wip" ]]; do
    read -p "worker nfs ip?" wip
done
while [[ -z "$whome" && "$role" == "worker" ]]; do
    read -p "worker home?" whome
done

echo "role: $role"
echo "cip: $cip"
echo "chome: $chome"
echo "wip: $wip"
echo "whome: $whome"

if yesno "proceed?"; then
    systemctl start nfs
    systemctl enable nfs

    if [[ "$role" == "controller" ]]; then
        mkdir -p "$chome"
        mkdir -p "$chome/tlv"
        setfacl -d -m g::rwx -m o::rwx -R "$chome/tlv"
        exports_string="$chome/tlv $wip/32(rw,sync,fsid=0)"
        grep "$exports_string" /etc/exports
        if [[ $? -ne 0 ]]; then
            echo "$exports_string" >> /etc/exports
            exportfs -ra
        fi
    elif [[ "$role" == "worker" ]]; then
        mkdir -p "$whome"
        mkdir -p "$whome/tlv"
        fstab_string="$cip:$chome/tlv $whome/tlv nfs rw,sync,nfsvers=3 0 0"
        grep "$fstab_string" /etc/fstab
        if [[ $? -ne 0 ]]; then
            echo "$fstab_string" >> /etc/fstab
            mount -a
        fi
    fi
fi